import { defineStore } from "pinia";

const counterStore = defineStore("counter", {
  // state: 状态
  state: () => ({
    count: 0,
    friends: [
      { id: 111, name: "getters-pinia1" },
      { id: 112, name: "getters-pinia2" },
      { id: 113, name: "getters-pinia3" },
    ],
  }),
  getters: {
    // 1.基本使用
    doubleCount(state) {
      return state.count * 2;
    },
    // 2.一个getter引入另外一个getter
    doubleCountAddOne() {
      // this是store实例
      return this.doubleCount + 1;
    },
    // 3.getters也支持返回一个函数
    getFriendById(state) {
      return function (id) {
        // for (let i = 0; i < state.friends.length; i++) {
        //   const friend = state.friends[i]
        //   if (friend.id === id) {
        //     return friend
        //   }
        // }
        return state.friends.find((item) => item.id === id);
      };
    },
  },
  actions: {
    increment() {
      this.count++;
    },
    incrementNum(num) {
      this.count += num;
    },
    addSupper() {
      this.incrementNum(100);
    },
  },
});

export default counterStore;
